package common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 登录拦截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter{
	private static final String LOGIN_URL = "/login";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
		System.out.println("-------- LoginInterceptor -- preHandle() | requestURI: " + request.getRequestURI());
		
		//请求到登陆页，正常跳转 —— 此处可通过mvc:exclude-mapping配置（见mvc-context.xml）
		System.out.println("request.getServletPath(): " + request.getServletPath());
		if(request.getServletPath().startsWith(LOGIN_URL)) {
			return true;
		}
		
		//已登录，正常跳转
		if(null != request.getSession().getAttribute("username")) {
			return true;
		}
		
		//重定向到登录界面
		response.sendRedirect(request.getContextPath() + LOGIN_URL);
		return false;
	}
}
